package com.nf.health.app.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract.Columns;
import android.text.TextUtils;

import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.util.HanziToPinyin;
import com.nf.health.app.Constants;
import com.nf.health.app.MyApplication;
import com.nf.health.app.models.GroupInfo;
import com.nf.health.app.models.GroupManagerInfo;
import com.nf.health.app.inquiry.bean.PatientUser;
import com.nf.health.app.inquiry.bean.QuestionMsg;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * Created by Jason on 2016/3/11.
 * 管理所有数据库表的增删改查操作
 */
public class DbManager {

    static private DbManager dbMgr = new DbManager();
    private DbOpenHelper dbHelper;
    private DbManager(){
        dbHelper = DbOpenHelper.getInstance(MyApplication.getInstance());
    }

    public static synchronized DbManager getInstance(){
        if(dbMgr == null){
            dbMgr = new DbManager();
        }
        return dbMgr;
    }

    public long savePatient(PatientUser user){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(PatientDao.COLUMN_NAME_NICK, user.getNick());
        values.put(PatientDao.COLUMN_NAME_GENDER, user.getGender());
        values.put(PatientDao.COLUMN_NAME_BIRTHDAY, user.getBirthday());
        values.put(PatientDao.COLUMN_NAME_CHECKED, user.getChecked());
        if(db.isOpen()){
            return db.replace(PatientDao.TABLE_NAME, null, values);
        }
        return -1;
    }

    /**
     * 保存好友list
     *
     * @param contactList
     */
    synchronized public void saveContactList(List<EaseUser> contactList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(UserDao.TABLE_NAME, null, null);
            for (EaseUser user : contactList) {
                ContentValues values = new ContentValues();
                values.put(UserDao.COLUMN_NAME_ID, user.getUsername());
                if(user.getNick() != null)
                    values.put(UserDao.COLUMN_NAME_NICK, user.getNick());
                if(user.getAvatar() != null)
                    values.put(UserDao.COLUMN_NAME_AVATAR, user.getAvatar());
                db.replace(UserDao.TABLE_NAME, null, values);
            }
        }
    }

    synchronized public EaseUser getContact(String username){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        EaseUser user = new EaseUser(username);
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + UserDao.TABLE_NAME +" where "+UserDao.COLUMN_NAME_ID+"=?", new String[]{username});
            if (cursor.moveToNext()) {
                String nick = cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_NICK));
                String avatar = cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_AVATAR));
                user.setNick(nick);
                user.setAvatar(avatar);
            }
            cursor.close();
        }
        return user;
    }
    /**
     * 获取好友list
     *
     * @return
     */
    synchronized public Map<String, EaseUser> getContactList() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Map<String, EaseUser> users = new Hashtable<String, EaseUser>();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + UserDao.TABLE_NAME /* + " desc" */, null);
            while (cursor.moveToNext()) {
                String username = cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_ID));
                String nick = cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_NICK));
                String avatar = cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_AVATAR));
                EaseUser user = new EaseUser(username);
                user.setNick(nick);
                user.setAvatar(avatar);
                String headerName = null;
                if (!TextUtils.isEmpty(user.getNick())) {
                    headerName = user.getNick();
                } else {
                    headerName = user.getUsername();
                }
                if(TextUtils.isEmpty(username)){
                    continue;
                }else if (username.equals(Constants.NEW_FRIENDS_USERNAME) || username.equals(Constants.GROUP_USERNAME)
                        || username.equals(Constants.CHAT_ROOM)|| username.equals(Constants.CHAT_ROBOT)) {
                    user.setInitialLetter("");
                } else if (Character.isDigit(headerName.charAt(0))) {
                    user.setInitialLetter("#");
                } else {
                    user.setInitialLetter(HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
                    char header = user.getInitialLetter().toLowerCase().charAt(0);
                    if (header < 'a' || header > 'z') {
                        user.setInitialLetter("#");
                    }
                }
                users.put(username, user);
            }
            cursor.close();
        }
        return users;
    }

    /**
     * 删除一个联系人
     * @param username
     */
    synchronized public void deleteContact(String username){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            db.delete(UserDao.TABLE_NAME, UserDao.COLUMN_NAME_ID + " = ?", new String[]{username});
        }
    }

    /**
     * 保存一个联系人
     * @param user
     */
    synchronized public void saveContact(EaseUser user){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(UserDao.COLUMN_NAME_ID, user.getUsername());
        if(user.getNick() != null)
            values.put(UserDao.COLUMN_NAME_NICK, user.getNick());
        if(user.getAvatar() != null)
            values.put(UserDao.COLUMN_NAME_AVATAR, user.getAvatar());
        if(db.isOpen()){
            db.replace(UserDao.TABLE_NAME, null, values);
        }
    }
    /**
     * 保存一个联系人
     * @param
     * 目前此方法不起作用
     */
    /*synchronized public void saveContact(String name ,String nick,String avatar ){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(UserDao.COLUMN_NAME_ID, name);
        if(!TextUtils.isEmpty(nick))
            values.put(UserDao.COLUMN_NAME_NICK,nick);
        if(TextUtils.isEmpty(avatar))
            values.put(UserDao.COLUMN_NAME_AVATAR, avatar);
        if(db.isOpen()){
            db.replace(UserDao.TABLE_NAME, null, values);
        }
    }*/
    /**
     * 保存一条信息
     * @param questionMsg
     */
    synchronized public void saveQuestion(QuestionMsg questionMsg){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(QuestionDao.COLUMN_QUESTION_ID, questionMsg.getqId());
        values.put(QuestionDao.COLUMN_USRE_DESCRIPTION, questionMsg.getUserDesc());
        values.put(QuestionDao.COLUMN_QUESTION_CONTENT, questionMsg.getContent());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < questionMsg.getImages().size(); i++) {
            String url = questionMsg.getImages().get(i);
            sb.append(url);
            if(i!=questionMsg.getImages().size()-1){
                sb.append(",");//地址用“,”逗号隔开
            }
        }
        values.put(QuestionDao.COLUMN_IMAGES, sb.toString());
        if(db.isOpen()){
            db.replace(QuestionDao.TABLE_NAME, null, values);
        }
    }

    synchronized public void closeDB(){
        if(dbHelper != null){
            dbHelper.closeDB();
        }
        dbMgr = null;
    }

    public int updatePatient() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(PatientDao.COLUMN_NAME_CHECKED, 0);
        if(db.isOpen()){
            return db.update(PatientDao.TABLE_NAME, values, PatientDao.COLUMN_NAME_CHECKED + "= ?", new String[]{"1"});
        }
        return -1;
    }

    public PatientUser getPatientUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + PatientDao.TABLE_NAME + " where " +PatientDao.COLUMN_NAME_CHECKED+"=?", new String[]{"1"});
            if(cursor.moveToNext()){
                String nick = cursor.getString(cursor.getColumnIndex(PatientDao.COLUMN_NAME_NICK));
                int gender = cursor.getInt(cursor.getColumnIndex(PatientDao.COLUMN_NAME_GENDER));
                int id = cursor.getInt(cursor.getColumnIndex(Columns._ID));
                int checked = cursor.getInt(cursor.getColumnIndex(PatientDao.COLUMN_NAME_CHECKED));
                String birthday = cursor.getString(cursor.getColumnIndex(PatientDao.COLUMN_NAME_BIRTHDAY));
                PatientUser user = new PatientUser();
                user.setChecked(checked);
                user.setBirthday(birthday);
                user.setGender(gender);
                user.setNick(nick);
                user.setId(id);
                return user;
            }
        }
        return null;
    }

    public List<PatientUser> getPatientUsers(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ArrayList<PatientUser> users = new ArrayList<>();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + PatientDao.TABLE_NAME /* + " desc" */, null);
            while (cursor.moveToNext()) {
                String nick = cursor.getString(cursor.getColumnIndex(PatientDao.COLUMN_NAME_NICK));
                int gender = cursor.getInt(cursor.getColumnIndex(PatientDao.COLUMN_NAME_GENDER));
                int id = cursor.getInt(cursor.getColumnIndex(Columns._ID));
                int checked = cursor.getInt(cursor.getColumnIndex(PatientDao.COLUMN_NAME_CHECKED));
                String birthday = cursor.getString(cursor.getColumnIndex(PatientDao.COLUMN_NAME_BIRTHDAY));
                PatientUser user = new PatientUser();
                user.setChecked(checked);
                user.setBirthday(birthday);
                user.setGender(gender);
                user.setNick(nick);
                user.setId(id);
                users.add(user);
            }
        }
        return users;
    }

    public int deletePatient(Integer id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            return db.delete(PatientDao.TABLE_NAME, Columns._ID + " = ?", new String[]{String.valueOf(id)});
        }
        return -1;
    }
    /**
     * 获取一条问题信息
     */
    public QuestionMsg findQuestion(String id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + QuestionDao.TABLE_NAME +" where "+QuestionDao.COLUMN_QUESTION_ID+" =?", new String[]{id});
            if (cursor.moveToNext()) {
                String qId = cursor.getString(cursor.getColumnIndex(QuestionDao.COLUMN_QUESTION_ID));
                String userDesc = cursor.getString(cursor.getColumnIndex(QuestionDao.COLUMN_USRE_DESCRIPTION));
                String content = cursor.getString(cursor.getColumnIndex(QuestionDao.COLUMN_QUESTION_CONTENT));
                String images = cursor.getString(cursor.getColumnIndex(QuestionDao.COLUMN_IMAGES));
                QuestionMsg questionMsg = new QuestionMsg();
                questionMsg.setqId(qId);
                questionMsg.setContent(content);
                questionMsg.setUserDesc(userDesc);
                if(!TextUtils.isEmpty(images)){
                    ArrayList<String> urls = new ArrayList<>();
                    String[] urlArray = images.split(",");
                    for (int i = 0; i < urlArray.length; i++) {
                        urls.add(urlArray[i]);
                    }
                    questionMsg.setImages(urls);
                }else{
                    questionMsg.setImages(new ArrayList<String>());
                }
                return questionMsg;
            }
        }
        return null;
    }
    /**
     *存储一条会话信息时间
     */
    synchronized public void saveChatTime(String userid,String time){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ChatTimeDao.COLUMN_USER_ID, userid);
        values.put(ChatTimeDao.COLUMN_TIME, time);
        if(db.isOpen()){
            db.replace(ChatTimeDao.TABLE_NAME, null, values);
        }
    }

    /**
     * 根据id取出时间
     * @param id 用户id或者群聊id
     * @return 记录的时间,或者""
     */
    public String findChatTimeById(String id) {
        String time = "";
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + ChatTimeDao.TABLE_NAME +" where "+ChatTimeDao.COLUMN_USER_ID+" =?", new String[]{id});
            if (cursor.moveToNext()) {
                time = cursor.getString(cursor.getColumnIndex(ChatTimeDao.COLUMN_TIME));
            }else{
                time = "";
            }
        }
        return time;
    }

    /* 保存群主及其状态 集合
    * @param contactList
    */
    synchronized public void saveGroupStateList(List<GroupInfo> contactList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(GroupInfoDao.TABLE_NAME, null, null);
            for (GroupInfo user : contactList) {
                ContentValues values = new ContentValues();
                values.put(GroupInfoDao.COLUMN_NAME_ID, user.getUsername());
                if(user.getIsForbit() != null)
                    values.put(GroupInfoDao.IS_FORBIT_TALK, user.getIsForbit());
                db.replace(GroupInfoDao.TABLE_NAME, null, values);
            }
        }
    }
    /* 保存群主及其状态 增加一个群组 及其状态
     * @param contactList
     */
    synchronized public void addOneGroupState(GroupInfo user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            ContentValues values = new ContentValues();
            values.put(GroupInfoDao.COLUMN_NAME_ID, user.getUsername());
            values.put(GroupInfoDao.IS_FORBIT_TALK, user.getIsForbit());
            db.replace(GroupInfoDao.TABLE_NAME, null, values);
        }

    }
    /* 保存群主及其状态 增加一个群组 及其状态
     * @param contactList
     */
    synchronized public void insertOneGroupState(GroupInfo user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            ContentValues values = new ContentValues();
            values.put(GroupInfoDao.COLUMN_NAME_ID, user.getUsername());
            values.put(GroupInfoDao.IS_FORBIT_TALK, user.getIsForbit());
            db.insert(GroupInfoDao.TABLE_NAME, null, values);
        }

    }
    /* 获取一个群组 及其状态
     * @param contactList
     */
    synchronized public GroupInfo  getOneGroupState(String groupId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        GroupInfo userInfo = new GroupInfo();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + GroupInfoDao.TABLE_NAME +" where "+GroupInfoDao.COLUMN_NAME_ID+" =?", new String[]{groupId});
            if (cursor.moveToNext()) {
                String  username = cursor.getString(cursor.getColumnIndex(GroupInfoDao.COLUMN_NAME_ID));
                String  forBitState = cursor.getString(cursor.getColumnIndex(GroupInfoDao.IS_FORBIT_TALK));
                userInfo.setUsername(username);
                userInfo.setIsForbit(forBitState);
            }
            cursor.close();
        }
        return userInfo;
    }
    /*
    *  修改群主及其状态 增加一个群组 及其状态
    @param contactList
    */
    synchronized public void upOneGroupState(GroupInfo user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(GroupInfoDao.IS_FORBIT_TALK, user.getIsForbit());//key为字段名，value为值
        db.update(GroupInfoDao.TABLE_NAME, values, GroupInfoDao.COLUMN_NAME_ID + " = ?", new String[]{user.getUsername()});
        db.close();
    }
    /**
     * 删除一个群组 及其状态
     * @param username
     */
    synchronized public void deleteOneGroupState(String username){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            db.delete(GroupInfoDao.TABLE_NAME, GroupInfoDao.COLUMN_NAME_ID + " = ?", new String[]{username});
        }
    }
    /* 保存群主的id及名字
     * @param contactList
     */
    synchronized public void addGroupManagerList(List<GroupManagerInfo> list) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            for(GroupManagerInfo user : list){
                ContentValues values = new ContentValues();
                values.put(GroupManagerInfoDao.COLUMN_NAME_ID, user.getGroupId());
                values.put(GroupManagerInfoDao.name, user.getUsername());
                if(!TextUtils.isEmpty(user.getNickName())){
                    values.put(GroupManagerInfoDao.nickName, user.getNickName());
                }
                db.replace(GroupManagerInfoDao.TABLE_NAME, null, values);
            }
        }
    }
    /* 保存群主的id及名字
     * @param contactList
     */
    synchronized public void addoneGroupManager(GroupManagerInfo user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
                ContentValues values = new ContentValues();
                values.put(GroupManagerInfoDao.COLUMN_NAME_ID, user.getGroupId());
                values.put(GroupManagerInfoDao.name, user.getUsername());
                if(!TextUtils.isEmpty(user.getNickName())){
                    values.put(GroupManagerInfoDao.nickName, user.getNickName());
                }
                db.replace(GroupManagerInfoDao.TABLE_NAME, null, values);
        }
        db.close();
    }
    /* 根据群主的id得到名字
     * @param contactList
     */
    synchronized public String getOneGroupManager(String groupId) {

        String name = "";
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            Cursor cursor = db.rawQuery("select * from " + GroupManagerInfoDao.TABLE_NAME +" where "+GroupManagerInfoDao.COLUMN_NAME_ID+" =?", new String[]{groupId});
            if (cursor.moveToNext()) {
                name = cursor.getString(cursor.getColumnIndex(GroupManagerInfoDao.name));
            }
            cursor.close();
        }
        db.close();
        return name;
    }
}
